'use strict';
//获取数据库的引用
const db = uniCloud.database(); 
// 获取集合的引用 表
const helpcollection = db.collection('help');
exports.main = async (event, context) => {
let type = event.type;
if(type == 0){
	//插入操作
	let { oldId,oldCNlocation,oldlatitude,oldlongitude,
	      volunId,volunCNlocation,volunlatitude,volunlongitude,
	      matching,helpComplete,completeTime,randomNumber,oldRate,volunRate } = event
	let res = await helpcollection.add({
		oldId,oldCNlocation,oldlatitude,oldlongitude,
		volunId,volunCNlocation,volunlatitude,volunlongitude,
		matching,helpComplete,completeTime,randomNumber,
		oldRate,volunRate
	})
	return res;
}else if(type == 1){
	//查询操作
	let eventId = event.eventId;
	let res = await helpcollection.where({	
        _id:eventId
	}).get()
	
	return res;
	
}else if(type == 2){
	//删除操作
	let deleteId = event.eventId;
	if(deleteId){
	 let res = await helpcollection.where({
	    _id:deleteId
	}).remove()
	return res;
	}	
}else{
	//志愿者查找帮助
	let { volunId,volunCNlocation,volunlatitude,volunlongitude } = event
	if(volunCNlocation){
		console.log("志愿者地址：");
		console.log(volunCNlocation);
		console.log(volunlatitude);
		console.log(volunlongitude);
		let findres = await helpcollection.where({
	    oldCNlocation:volunCNlocation,
		matching:0,
	}).get()
	if(findres.affectedDocs == 1){
		let helpId = findres.data[0]._id;
		const sjNumber = getRandomIntInclusive(1000,9999).toString();
		let updataRes = await helpcollection.doc(helpId).update({
		  volunId:volunId,
		  volunCNlocation:volunCNlocation,
		  volunlatitude:volunlatitude,
		  volunlongitude:volunlongitude,
		  matching:1,
		  randomNumber:sjNumber,
		  
		});
		let res = await helpcollection.where({
		     _id:helpId
		}).get()
		return res;
	}else{
		return findres
	}




	
	}
}
};

function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值，含最小值 
  } 